package com.codeberry.yws;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Main Server Class
 */
public class YoctoWebServer implements Runnable {
  private int port;
  private ServerSocket serverSocket;
  private Thread thread;
  private ContextMap contextMap;
  private ContextHandler initHandler;

  public YoctoWebServer(int port, ContextHandler defaultContextHandler) {
    this.port = port;

    contextMap = new ContextMap(defaultContextHandler);
  }

  public void putContext(ContextHandler contextHandler) {
    contextMap.put(contextHandler.getContextPath(), contextHandler);
  }

  public void start() throws IOException {
    serverSocket = new ServerSocket(port);

    thread = new Thread(this, YoctoWebServer.class.getSimpleName());
    thread.start();
  }

  public void stop() {
    thread = null;
    if (serverSocket != null) {
      try {
        serverSocket.close();
      } catch (IOException ignore) {
      }
      serverSocket = null;
    }
  }

  public void run() {
    while (thread == Thread.currentThread()) {
      try {
        Socket socket = serverSocket.accept();
        YConnectionHandler handler = new YConnectionHandler(socket,
                                                            initHandler,
                                                            contextMap);
        handler.start();
      } catch (IOException e) {
        e.printStackTrace();
        if (serverSocket.isClosed()) {
          break;
        }
      }
    }

    System.out.println("Server Shut Down");
  }

  public void setInitHandler(ContextHandler initHandler) {
    this.initHandler = initHandler;
  }
}
